package com.example.fiction.service;

import android.support.annotation.NonNull;
import android.util.Log;

import com.example.fiction.base.BaseResponse;
import com.example.fiction.exception.ResponseException;
import com.example.fiction.utils.RetrofitClientUtils;

import org.json.JSONException;

import java.io.IOException;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.functions.Function;
import retrofit2.http.FieldMap;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;

/**
 * author: 姚鸿杰
 * time: 2019/4/17 22:53
 **/
public class BooksLoader {

    private final String TAG = "BooksLoader";
    private Observable<BaseResponse> api;

    public BooksLoader(@NonNull String data, String method) throws IOException, JSONException {
        Map<String, String> map = ApiArgs.getApiArgs(data, method);
        if (map != null)
            api = RetrofitClientUtils.execute(RetrofitClientUtils.getInstance().create(BooksApi.class).getBooksInfo(map));
    }

    public Observable<String> getBooks() {
        if (api != null) {
            return api.map(new Function<BaseResponse, String>() {
                @Override
                public String apply(BaseResponse response) throws ResponseException, IOException, JSONException {
                    Log.e(TAG, response.toString());
                    return ApiArgs.verifyArgs(response);
                }
            });
        } else {
            return null;
        }
    }

    public interface BooksApi {
        @FormUrlEncoded
        @POST("books")
        Observable<BaseResponse> getBooksInfo(@FieldMap Map<String, String> args);
    }
}
